package com.cyzy.chatai.controller;

import com.cyzy.chatai.service.AiChatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/ai")
@CrossOrigin(origins = "*")
public class AiController {

    private static final Logger logger = LoggerFactory.getLogger(AiController.class);

    private final AiChatService aiChatService;

    // 构造器注入
    public AiController(AiChatService aiChatService) {
        this.aiChatService = aiChatService;
    }

    /**
     * AI聊天API端点
     */
    @PostMapping("/chat")
    public ResponseEntity<Map<String, Object>> aiChat(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String message = (String) request.get("message");
            String user = (String) request.get("user");

            if (message == null || message.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "消息内容不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            // 调用AI服务
            String aiReply = aiChatService.sendMessage(message, user);

            response.put("success", true);
            response.put("content", aiReply);
            response.put("user", user);

            logger.info("AI聊天API调用 - 用户: {}, 消息: {}", user, message);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "AI服务异常: " + e.getMessage());
            logger.error("AI聊天API异常: {}", e.getMessage(), e);
        }
        return ResponseEntity.ok(response);
    }

    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "UP");
        response.put("service", "ChatAI Service");
        logger.info("AI健康检查API调用 - 服务状态: UP");
        return ResponseEntity.ok(response);
    }
}
